package org.cove.ape {
	import trace;
	import de.gameduell.framework.debug.Debug;	
	
	/**
	 * @author Ferry Trunschke
	 */
	public class HeuristicMovementStateListener {
		
		public var movingParticles:Array = new Array();
		public var restingParticles:Array = new Array();

		public function HeuristicMovementStateListener() {
		}
		
		public function clone(cloneEngine:APEngine):HeuristicMovementStateListener {
			var clone:HeuristicMovementStateListener = new HeuristicMovementStateListener();
			clone.movingParticles  = Cloner.cloneArray(cloneEngine, this.movingParticles);
			clone.restingParticles = Cloner.cloneArray(cloneEngine, this.restingParticles);
			return clone;
		}
		
		/**
		 * call on every creation, integration or collision, fixed changes
		 * @param one
		 */
		public function onChange(one:AbstractParticle):void {
			if (one.isStopped() || one.fixed) {
				onStop(one);
			}
			else {
				onMovement(one);
				
			}
		}
		
		public function update(allParticles:Array):void{
			for(var i in allParticles){
				onChange(allParticles[i]);
			}
		}
		
		public function onStop(one:AbstractParticle):void {
			// add as stopped
			if (restingParticles.indexOf(one) == -1) {
				restingParticles.push(one);
//				Debug.trace("HeuristicMovementStateListener add stopped particle "+restingParticles.length);
			}
			
			// remove as moving 
			var index:int = movingParticles.indexOf(one);
			if (index >= 0) {
				movingParticles = movingParticles.slice(0, index).concat(movingParticles.slice(index+1, movingParticles.length));
//				Debug.trace("HeuristicMovementStateListener  remove moving particle "+movingParticles.length);
			}
		}
	
		public function onMovement(one:AbstractParticle):void {
			// add as moving
			if (movingParticles.indexOf(one) == -1) {
				movingParticles.push(one);
//				Debug.trace("HeuristicMovementStateListener  add moving particle "+movingParticles.length);
			}
			
			// remove as stopped
			var index:int = restingParticles.indexOf(one);
			if (index >= 0) {
				restingParticles = restingParticles.slice(0, index).concat(restingParticles.slice(index+1, restingParticles.length));
//				Debug.trace("HeuristicMovementStateListener removed stopped particle "+restingParticles.length);
			}
			
		}
	}
}
